import axios from 'axios'
import fetchJsonp from 'fetch-jsonp'
const service = axios.create({
    baseURL: process.env.NODE_ENV === 'development' ? '/api' : "https://supplier.alibaba.com",
    timeout: 50000
})
// http request 拦截器
service.interceptors.request.use(
    (config) => {
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)
// http response 拦截器
service.interceptors.response.use(
    (response) => {
        return response.data
    },
    (error) => {
        return Promise.reject(error)
    }
)

const serviceWidget = axios.create({
    baseURL: process.env.NODE_ENV === 'development' ? '/widget' : "https://widget.1688.com",
    timeout: 50000
})
// http request 拦截器
serviceWidget.interceptors.request.use(
    (config) => {
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)
// http response 拦截器
serviceWidget.interceptors.response.use(
    (response) => {
        return response.data
    },
    (error) => {
        return Promise.reject(error)
    }
)

const httpJsonp = (url: string, params: Record<string, string | number>) => {
	const tempParams = Object.entries(params)
		.reduce((res, next) => {
			return `${res}&${next[0]}=${encodeURIComponent(next[1])}`;
		}, "")
		.slice(1);
	return fetchJsonp(url + "?" + tempParams).then((res) => res.json());
};


export {
    service,
    serviceWidget,
    httpJsonp
}
